package cn.topcodes.tcsf.wechat.web.controller;

import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMp;
import cn.topcodes.tcsf.wechat.domain.vo.WechatMpVo;
import cn.topcodes.tcsf.wechat.domain.form.WechatMpForm;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.wechat.service.WechatMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 微信公众号管理控制器
 * @author Unicorn
 * @date 2018-03-20 15:56:31
 */
@Controller
@RequestMapping("/admin/wechat-mp")
public class WechatMpController extends AdminController<WechatMp,WechatMpVo,WechatMpForm> {

	@Autowired
	private WechatMpService wechatMpService;

	@Override
	protected String getPageFolder() {
		return "wechat/admin/wechat-mp";
	}

	@ResponseBody
	@RequestMapping(value = "set-current-mp", method = RequestMethod.POST)
	public ApiResponseEntity setCurrentMp(
			@RequestParam Long wechatMpId,
			@RequestParam String password
	) {
		if(!this.validateOperation(password)) {
			return ApiResponseEntity.buildFailed("密码错误");
		}
		wechatMpService.setCurrentMp(wechatMpId);
		return ApiResponseEntity.buildOK();
	}

	@ResponseBody
	@RequestMapping(value = "set-default-mp", method = RequestMethod.POST)
	public ApiResponseEntity setDefaultMp(
			@RequestParam String mpId,
			@RequestParam String password
	) {
		if(!this.validateOperation(password)) {
			return ApiResponseEntity.buildFailed("密码错误");
		}
		wechatMpService.setDefaultMpId(mpId);
		return ApiResponseEntity.buildOK();
	}

	@Override
	protected List<WechatMpVo> entity2Vo(List<WechatMp> entitys, HttpServletRequest request) {
		List<WechatMpVo> list = super.entity2Vo(entitys, request);
		for(WechatMpVo vo : list) {
			if(vo.getMpId().equals(wechatMpService.getCurrentMpId())) {
				vo.setIsCurrent(true);
			}else {
				vo.setIsCurrent(false);
			}
			if(vo.getMpId().equals(wechatMpService.getDefaultMpId())) {
				vo.setIsDefault(true);
			}else {
				vo.setIsDefault(false);
			}
		}
		return list;
	}
}
